<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    append-to-body
    :close-on-click-modal="false"
    @close="closeDialog()"
    :visible="visible"
    width="1000px"
    top="30px"
  >
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="100px">
      <el-collapse v-model="activeNames">
        <el-collapse-item name="1">
          <template slot="title">
            <div>
              <i class="header-icon el-icon-goods"></i>
              <span class="title-size">基本信息</span>
            </div>
          </template>
          <el-row style="margin-top:20px">
            <el-form-item label="文章标题" prop="articleTitle">
              <el-input v-model="dataForm.articleTitle" placeholder="请输入文章标题" ></el-input>
            </el-form-item>
          </el-row>

          <el-row>
            <el-form-item label="文章轮播图" prop="articleImages">
              <ImagesUpload v-model="dataForm.articleImages"></ImagesUpload>
            </el-form-item>
          </el-row>
          <el-row>
            <el-form-item label="作者头像" prop="articleHeader">
              <ImageUploadSingle v-model="dataForm.articleHeader"></ImageUploadSingle>
            </el-form-item>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="文章分类" prop="categoryId">
                <el-select
                  v-model="dataForm.categoryId"
                  filterable
                  placeholder="请选择文章分类"
                  clearable
                  style="width:100%"
                >
                  <el-option
                    v-for="dict in articleCategoryList"
                    :key="dict.id"
                    :label="dict.categoryName"
                    :value="dict.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="作者名称" prop="articleAuthor">
                <el-input v-model="dataForm.articleAuthor" placeholder="请输入作者名称" ></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item label="是否显示" prop="status">
                <el-radio-group v-model="dataForm.status">
                  <el-radio label="1" border>启用</el-radio>
                  <el-radio label="0" border>关闭</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="文章简介" prop="articleSnapshot">
                <el-input v-model="dataForm.articleSnapshot" placeholder="请输入文章简介" ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <el-collapse-item name="2">
          <template slot="title">
            <div>
              <i class="header-icon el-icon-s-order"></i>
              <span class="title-size">文章内容</span>
            </div>
          </template>
          <el-row>
            <el-form-item label="文章内容" prop="content">
              <quill-editor
                  class="editor"
                  v-model="dataForm.content"
                  ref="myQuillEditor"
                  :options="editorOption">
              </quill-editor>
            </el-form-item>
          </el-row>
        </el-collapse-item>

      </el-collapse>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" v-if="canSubmit"
        >确定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { getObj, addObj, putObj } from "@/api/article/article";
import {goodsArticleCategoryList} from '@/api/article/category';
import ImagesUpload from "@/components/imagesUpload";
import ImageUploadSingle from '@/components/imageUploadSingle';
import { quillEditor } from 'vue-quill-editor'


import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

export default {
  props:{
    visible: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      activeNames:['1', '2'],
      canSubmit: false,
      dataForm: {
        status:'1',
        articleImages:[],
        articleHeader:null
      },
      dataRule: {
        articleTitle: [
          { required: true, message: "文章标题不能为空", trigger: "blur" },
        ],
        articleImages: [
          { required: true, message: "文章轮播图不能为空", trigger: "blur" },
        ],
        articleHeader: [
          { required: true, message: "作者头像不能为空", trigger: "blur" },
        ],
        categoryId: [
          { required: true, message: "文章分类不能为空", trigger: "blur" },
        ],
        articleAuthor: [
          { required: true, message: "作者名称不能为空", trigger: "blur" },
        ],
        articleTitle: [
          { required: true, message: "文章标题不能为空", trigger: "blur" },
        ],
        status: [
          { required: true, message: "是否显示不能为空", trigger: "blur" },
        ],
        content: [
          { required: true, message: "文章内容不能为空", trigger: "blur" },
        ]
      },
      articleCategoryList:[],

      // 富文本编辑器配置
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            ['blockquote', 'code-block'], // 引用  代码块
            [{ header: 1 }, { header: 2 }], // 1、2 级标题
            [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
            [{ script: 'sub' }, { script: 'super' }], // 上标/下标
            [{ indent: '-1' }, { indent: '+1' }], // 缩进
            [{ direction: 'rtl' }], // 文本方向
            [{ size: ['small', false, 'large', 'huge'] }], // 字体大小
            [{ header: [1, 2, 3, 4, 5, 6] }], // 标题
            [{ color: [] }, { background: [] }], // 字体颜色、字体背景颜色
            // [{ font: ['songti'] }], // 字体种类
            [{ align: [] }], // 对齐方式
            ['clean'], // 清除文本格式
            ['image', 'video'] // 链接、图片、视频
          ]
        },
        placeholder: '请输入正文'
      },
    };
  },
  components: {
    ImagesUpload,
    ImageUploadSingle,
    quillEditor
  },
  methods: {
    init(id) {
      this.canSubmit = true;
      this.goodsArticleCategoryList()
      if(id){
        getObj(id).then((response) => {
          let data = response.data.data;
          // 处理头像
          if(data.articleHeader){
            let arr = JSON.parse(data.articleHeader)
            if(arr.length > 0){
              data.articleHeader = arr[0]
            }
          }

          // 处理轮播图
          if(data.articleImages){
            data.articleImages = JSON.parse(data.articleImages)
          }
          this.dataForm = data
          //this.dataForm.articleImages = this.dataForm.articleImages ? this.dataForm.articleImages.split(',') : []
        });
      }
    },

    /**
     * 获取商品分类
     */
    goodsArticleCategoryList(){
      goodsArticleCategoryList().then(res=>{
        this.articleCategoryList = res.data.data
      })
    },

    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.canSubmit = false;

          let requestData = JSON.parse(JSON.stringify(this.dataForm))
          requestData.articleHeader = requestData.articleHeader.materialId
          requestData.articleImages = requestData.articleImages.map(p=>p.materialId).join()
          if (requestData.id) {
            putObj(requestData)
              .then((data) => {
                this.$notify.success("修改成功");
                this.$emit("refreshDataList");
                this.closeDialog()
              })
              .catch(() => {
                this.canSubmit = true;
              });
          } else {
            addObj(requestData)
              .then((data) => {
                this.$notify.success("添加成功");
                this.$emit("refreshDataList");
                this.closeDialog()
              })
              .catch(() => {
                this.canSubmit = true;
              });
          }
        }
      });
    },
    //重置表单
    closeDialog() {
      this.$emit('update:visible', false)
    },
  },
};
</script>

<style scoped>
.editor {
  line-height: normal !important;
  height: 500px;
}
</style>